package serviceGoods

import (
	"context"
	goods_pb "mxshop/api/goods/v1"
	"mxshop/app/mxshop_api/api/internal/data"
	doGoods "mxshop/app/mxshop_api/api/internal/domain/do/goods"
	dtoGoods "mxshop/app/mxshop_api/api/internal/domain/dto/goods"
	srvGoods "mxshop/app/mxshop_api/api/internal/service/goods"
)

type BrandService struct {
	data data.DataFactory
}

func (bs *BrandService) BrandList(ctx context.Context, req *goods_pb.BrandFilterRequest) (*dtoGoods.BrandDTOList, error) {
	var ret dtoGoods.BrandDTOList

	rsp, err := bs.data.Goods().Brand().List(ctx, req)
	if err != nil {
		return nil, err
	}

	for _, v := range rsp.Items {
		ret.Items = append(ret.Items, &dtoGoods.BrandDTO{
			Id:   v.Id,
			Name: v.Name,
			Logo: v.Logo,
		})
	}
	ret.TotalCount = rsp.TotalCount

	return &ret, nil
}

func (bs *BrandService) CreateBrand(ctx context.Context, req *dtoGoods.BrandDTO) (*dtoGoods.BrandDTO, error) {
	var ret dtoGoods.BrandDTO

	brandDO := &doGoods.BrandDO{
		Name: req.Name,
		Logo: req.Logo,
	}
	if err := bs.data.Goods().Brand().Create(ctx, brandDO); err != nil {
		return nil, err
	}

	ret.Id = brandDO.Id

	return &ret, nil
}

func (bs *BrandService) DeleteBrand(ctx context.Context, req *dtoGoods.BrandDTO) error {
	return bs.data.Goods().Brand().Delete(ctx, req.Id)
}

func (bs *BrandService) UpdateBrand(ctx context.Context, req *dtoGoods.BrandDTO) error {
	return bs.data.Goods().Brand().Update(ctx, &doGoods.BrandDO{
		Id:   req.Id,
		Name: req.Name,
		Logo: req.Logo,
	})
}

func newBrand(data data.DataFactory) srvGoods.BrandSrv {
	return &BrandService{data: data}
}
